package com.hunter.api.handler;

import com.alibaba.fastjson.JSONObject;

import com.hunter.api.bean.EntityBean;
import com.hunter.api.help.exception.BusinessAssert;
import com.hunter.api.help.exception.BusinessException;
import com.hunter.api.help.result.BusinessCode;
import com.hunter.api.help.result.ErrorHelp;
import com.hunter.api.help.JsonHelper;
import com.hunter.api.help.result.SuccessHelp;
import com.hunter.api.mapper.EntityMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class EntityHandler {
    @Autowired
    private EntityMapper entityMapper;

    @Autowired
    private SqlHandler sqlHandler;

    /**
     /* EntityLv
     */
    public JSONObject EntityLv(EntityBean entity){
        JSONObject json = new JSONObject();
        JSONObject data = entity.getData();
        entity = entityMapper.EntityInfo(entity);
        //断言ENTITY不为空
        BusinessAssert.notNull(entity, BusinessCode.ENTITY_NOT_EXISTS);
        JSONObject lv_json = JSONObject.parseObject(entity.getLv_json());
        JSONObject futQuery = sqlHandler.queryAll(lv_json, data,1);
        json=new SuccessHelp("查询成功",futQuery).getResult();
        return json;
    }

    /**
     /* EntityInfo
     */
    public JSONObject EntityInfo(EntityBean entity){
        JSONObject json = new JSONObject();
        JSONObject data = entity.getData();
        entity = entityMapper.EntityInfo(entity);
        //断言ENTITY不为空
        BusinessAssert.notNull(entity, BusinessCode.ENTITY_NOT_EXISTS);
        JSONObject info_json = JSONObject.parseObject(entity.getInfo_json());
        JSONObject futQuery = sqlHandler.queryRow(info_json, data);
        json=new SuccessHelp("查询成功",futQuery).getResult();
        return json;
    }


    /**
     /* Entity
     */
    public JSONObject Entity(EntityBean entity,String sqlType)throws Exception{
        JSONObject json = new JSONObject();
        JSONObject data = entity.getData();
        entity = entityMapper.EntityInfo(entity);
        //断言ENTITY不为空
        BusinessAssert.notNull(entity, BusinessCode.ENTITY_NOT_EXISTS);
        JSONObject sql_json = null;
        JSONObject sqlUniqueCfg =null;
        switch (sqlType.toLowerCase()) {
            case "delete":
                sql_json = JSONObject.parseObject(entity.getDelete_json());
                break;
            case "enable":
                sql_json = JSONObject.parseObject(entity.getEnable_json());
                break;
            case "insert":
                sql_json = JSONObject.parseObject(entity.getInsert_json());
                sqlUniqueCfg = JSONObject.parseObject(entity.getUnique_insert_json());
                break;
            case "update":
                sql_json = JSONObject.parseObject(entity.getUpdate_json());
                sqlUniqueCfg = JSONObject.parseObject(entity.getUnique_update_json());
                break;
            default:
                log.error("invalid sql type: {}", sqlType);
                throw new BusinessException(BusinessCode.SQL_TYPE_ERROR);
        }

        String sql = sql_json.getString("sql");
        //拼接参数、验证必填参数： sql_json,paramsObj
        sql = sqlHandler.prepareSql(sql,sql_json, data);

        //断言sql不可能为空
        BusinessAssert.notNull(sql,BusinessCode.COMFIG_SQL_ERROR,String.format(" sql: %s, params: %s",sql,data));

        //如果唯一性验证不为空,则需要进行唯一性验证
        if (sqlUniqueCfg != null && "{}".equals(sqlUniqueCfg.toJSONString())) {
            //唯一性规则验证，多条规则需要合并成一条
            String sqlUnique= sqlUniqueCfg.getString("sql");
            int count = JsonHelper.getInteger(sqlHandler.queryScalar(sqlUniqueCfg,data),"value",0);
            //断言已经有重复项了
            BusinessAssert.isZero(count,BusinessCode.SQL_NOT_UNIQUE);
            JSONObject futQuery;
            //是否需要全量输入
            String is_in_all = JsonHelper.getString(data,"is_in_all","");
            if (StringUtils.isNotBlank(is_in_all)) {
                JSONObject info_json = JSONObject.parseObject(entity.getInfo_json());
                JSONObject info = sqlHandler.queryRow(info_json, data);

                futQuery = sqlHandler.execSql(sql_json, data,sqlType.toLowerCase(),info);
                info = sqlHandler.queryRow(info_json, data);
                if (sqlType.toLowerCase().equals("update")){
                    futQuery.put("value", info);
                }
            }else {
                futQuery = sqlHandler.execSql(sql_json, data,sqlType.toLowerCase());
                if (sqlType.toLowerCase().equals("update")){
                    JSONObject info_json = JSONObject.parseObject(entity.getInfo_json());
                    JSONObject info = sqlHandler.queryRow(info_json, data);
                    futQuery.put("value", info);
                }
            }
            json=new SuccessHelp("执行成功",futQuery).getResult();
        }else {
            JSONObject futQuery = sqlHandler.execSql(sql_json, data, sqlType.toLowerCase());
            json=new SuccessHelp("执行成功",futQuery).getResult();
        }
        return json;
    }


}
